<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="并发队列,">










<meta name="description" content="在多线程编程下，有时候我们需要使用现场安全的队列，其实队列大家多少肯定也知道点，比如消息中间件rabbitmq、rocketmq、kafka，都是一种生产者消费者模式，其实思想跟JDK给我们提供的并发队列相似，实际上消息队列肯定比并发队列难，要想学会跑还是得先学会走。 并发队列的类型一个线程安全的队列有两种形式：一种是使用阻塞算法，一种是使用非阻塞算法。使用阻塞算法可以用一个锁或者两个锁来控制入队">
<meta name="keywords" content="并发队列">
<meta property="og:type" content="article">
<meta property="og:title" content="Java并发编程六并发队列">
<meta property="og:url" content="https://zgsir.gitee.io/blog/2019/05/28/Java并发编程六并发队列/index.html">
<meta property="og:site_name" content="zhaoSir">
<meta property="og:description" content="在多线程编程下，有时候我们需要使用现场安全的队列，其实队列大家多少肯定也知道点，比如消息中间件rabbitmq、rocketmq、kafka，都是一种生产者消费者模式，其实思想跟JDK给我们提供的并发队列相似，实际上消息队列肯定比并发队列难，要想学会跑还是得先学会走。 并发队列的类型一个线程安全的队列有两种形式：一种是使用阻塞算法，一种是使用非阻塞算法。使用阻塞算法可以用一个锁或者两个锁来控制入队">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://s2.ax1x.com/2019/05/28/VmIpZR.png">
<meta property="og:image" content="https://s2.ax1x.com/2019/05/28/VmI9d1.png">
<meta property="og:image" content="https://s2.ax1x.com/2019/05/28/Vm5zL9.png">
<meta property="og:image" content="https://s2.ax1x.com/2019/05/28/VmIii6.png">
<meta property="og:image" content="https://s2.ax1x.com/2019/05/28/VmICIx.png">
<meta property="og:updated_time" content="2019-05-28T11:13:47.146Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Java并发编程六并发队列">
<meta name="twitter:description" content="在多线程编程下，有时候我们需要使用现场安全的队列，其实队列大家多少肯定也知道点，比如消息中间件rabbitmq、rocketmq、kafka，都是一种生产者消费者模式，其实思想跟JDK给我们提供的并发队列相似，实际上消息队列肯定比并发队列难，要想学会跑还是得先学会走。 并发队列的类型一个线程安全的队列有两种形式：一种是使用阻塞算法，一种是使用非阻塞算法。使用阻塞算法可以用一个锁或者两个锁来控制入队">
<meta name="twitter:image" content="https://s2.ax1x.com/2019/05/28/VmIpZR.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zgsir.gitee.io/blog/2019/05/28/Java并发编程六并发队列/">





  <title>Java并发编程六并发队列 | zhaoSir</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">zhaoSir</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">一个不正经的后台开发攻城狮</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/blog/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zgsir.gitee.io/blog/blog/2019/05/28/Java并发编程六并发队列/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zhaoSir">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/images/head.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zhaoSir">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Java并发编程六并发队列</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-05-28T19:07:51+08:00">
                2019-05-28
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于&#58;</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2019-05-28T19:13:47+08:00">
                2019-05-28
              </time>
            
          </span>
          
          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/Java并发/" itemprop="url" rel="index">
                    <span itemprop="name">Java并发</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-eye"></i> 阅读
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2.7k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  10分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>在多线程编程下，有时候我们需要使用现场安全的队列，其实队列大家多少肯定也知道点，比如消息中间件rabbitmq、rocketmq、kafka，都是一种生产者消费者模式，其实思想跟JDK给我们提供的并发队列相似，实际上消息队列肯定比并发队列难，要想学会跑还是得先学会走。</p>
<h1 id="并发队列的类型"><a href="#并发队列的类型" class="headerlink" title="并发队列的类型"></a>并发队列的类型</h1><p><strong>一个线程安全的队列有两种形式：一种是使用阻塞算法，一种是使用非阻塞算法。使用阻塞算法可以用一个锁或者两个锁来控制入队和出队的方式来实现，使用非阻塞算法可以用CAS方式来实现。</strong></p>
<h1 id="ConcurrentLinkedQueue"><a href="#ConcurrentLinkedQueue" class="headerlink" title="ConcurrentLinkedQueue"></a>ConcurrentLinkedQueue</h1><p><strong>ConcurrentLinkedQueue是一个基于单向链表无界无阻塞线程安全的队列，采用先进先出的规则对节点进行排序</strong>，当添加一个元素的时候，会被添加到队列的尾部，当获取一个元素的时候，会返回对头的元素，采用了CAS算法来实现。其中有两个volatile类型的Node节点来存储队列的首位节点，从下面的构造函数得值。<br><img src="https://s2.ax1x.com/2019/05/28/VmIpZR.png" alt="在这里插入图片描述"><br>既然是队列肯定要有生产和消费两个方法，offer是向队列尾部添加一个元素。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">Node(E item) &#123;</span><br><span class="line">            UNSAFE.putObject(this, itemOffset, item);</span><br><span class="line">        &#125;</span><br><span class="line">public boolean offer(E e) &#123;</span><br><span class="line">        // 判断不为null</span><br><span class="line">        checkNotNull(e);</span><br><span class="line">        // 构造Node节点 由内部unsafe提供的</span><br><span class="line">        final Node&lt;E&gt; newNode = new Node&lt;E&gt;(e);   </span><br><span class="line">      // 循环插入到队列尾部 p的初始值为队尾</span><br><span class="line">              for (Node&lt;E&gt; t = tail, p = t;;) &#123;                // （1） </span><br><span class="line">          // q 是 后继节点</span><br><span class="line">            Node&lt;E&gt; q = p.next;</span><br><span class="line">            // 判断q是否为null</span><br><span class="line">            if (q == null) &#123;                        // （2）</span><br><span class="line">                //  q 为null cas将入队节点添加到next</span><br><span class="line">                if (p.casNext(null, newNode)) &#123;           //（3）</span><br><span class="line">                    // 判断 p是否为尾节点 如果不是 cas修改入队节点到tail</span><br><span class="line">                    if (p != t) </span><br><span class="line">                        casTail(t, newNode);               // （4）</span><br><span class="line">                    return true;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            // 在多线程下，移除操作可能会head变为自引用，也就是head的next变成了head，</span><br><span class="line">            // 需要重新找到新的head</span><br><span class="line">            else if (p == q)</span><br><span class="line">                p = (t != (t = tail)) ? t : head;</span><br><span class="line">            else</span><br><span class="line">               // 有线程操作入队节点插入成功，重新修改p的值</span><br><span class="line">                p = (p != t &amp;&amp; t != (t = tail)) ? t : q;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>入队操作比较复杂，首先判断是为空，然后不停循环从尾部开始插入。比如线程A插入item1线程B插入item2，此时两个线程都到了（3）代码中，此时cas操作只有一个线程成功，线程A修改成功，插入队尾的后继节点返回，线程B失败，再次进入循环（1）中。<br><img src="https://s2.ax1x.com/2019/05/28/VmI9d1.png" alt="在这里插入图片描述"><br>此时由于线程A修改成功，B进入（2）发现next不为null会进入else if 先去判断节点是否移除，如果移除了则将p指向队头重新开始插入新节点，如果没有移除则修改p为q（q一开始为p的后继节点）。<br><img src="https://s2.ax1x.com/2019/05/28/Vm5zL9.png" alt="在这里插入图片描述"><br>然后再次进入到（1）中，当执行到（2）时候q是null。<br><img src="https://s2.ax1x.com/2019/05/28/VmIii6.png" alt="在这里插入图片描述"><br>由于q是null的，此时线程B通过cas操作item2入队，假如设置成功，因为此时还有可能别的线程修改，如果别的线程修改成功，则再进入（1）循环中。由于线程A插入成功后，线程B修改了p的值，所以p！=t，进入（4）修改tail节点为item2，然后退出循环。<br><img src="https://s2.ax1x.com/2019/05/28/VmICIx.png" alt="在这里插入图片描述"><br>poll方法是从对头取出一个元素，如果当没有元素则为空。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">public E poll() &#123;</span><br><span class="line">        // 死循环取元素</span><br><span class="line">        for (;;) &#123;</span><br><span class="line">        // p 指向头部元素</span><br><span class="line">            for (Node&lt;E&gt; h = head, p = h, q;;) &#123;</span><br><span class="line">                E item = p.item;</span><br><span class="line">                // 判断对头元素不为null 设置为空</span><br><span class="line">                if (item != null &amp;&amp; p.casItem(item, null)) &#123;</span><br><span class="line">                    // 判断p是否等于t 如果不等于，重新指向对头</span><br><span class="line">                    if (p != h) // hop two nodes at a time</span><br><span class="line">                        updateHead(h, ((q = p.next) != null) ? q : p);</span><br><span class="line">                    return item;</span><br><span class="line">                &#125;</span><br><span class="line">                // 队列为null 返回null</span><br><span class="line">                else if ((q = p.next) == null) &#123;</span><br><span class="line">                    updateHead(h, p);</span><br><span class="line">                    return null;</span><br><span class="line">                &#125;</span><br><span class="line">                // 有其他线程取出，重新入队</span><br><span class="line">                else if (p == q)</span><br><span class="line">                     continue restartFromHead;</span><br><span class="line">                else</span><br><span class="line">                    p = q;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>相比较添加，poll取出就很简单，只是从对头开始取元素，如果不为null则取走并且CAS设置为null，如果有线程已经取走，更新头部重新获取，如果队列为null，则返回null。<br><strong>注意：生产环境如果判断队列是否为null，使用isEmpty()而不使用size()&gt;0</strong>,。</p>
<h1 id="阻塞队列"><a href="#阻塞队列" class="headerlink" title="阻塞队列"></a>阻塞队列</h1><p>相比较ConcurrentLinkedQueue无阻塞队列，Java为我们提供了7种阻塞队列，在添加和移除的时候阻塞队列。阻塞队列常用语生产者消费者。</p>
<h2 id="方法说明"><a href="#方法说明" class="headerlink" title="方法说明"></a>方法说明</h2><table>
<thead>
<tr>
<th>方法</th>
<th>抛出异常</th>
<th>返回值</th>
<th>一直阻塞</th>
<th>超时退出</th>
</tr>
</thead>
<tbody>
<tr>
<td>插入方法</td>
<td>add（e）</td>
<td>offer（e）</td>
<td>put（e）</td>
<td>offer（e，time，unit）</td>
</tr>
<tr>
<td>移除方法</td>
<td>remove（）</td>
<td>poll（）</td>
<td>take（）</td>
<td>poll（time，unit）</td>
</tr>
<tr>
<td>检查方法</td>
<td>element（）</td>
<td>peek（）</td>
<td>不可用</td>
<td>不可用</td>
</tr>
</tbody>
</table>
<p><strong>抛出异常：如果队列已满，add抛出IllegalStateException(“Queue full”)异常，队列为空，remove抛出NoSuchElementException()。<br>返回值：offer成功返回true，失败返回false，poll时队列为null返回null。<br>一直阻塞：当队列满时，put则阻塞线程，等待不满；当队列为空时，take阻塞线程，等待不空，可以中断。<br>超时退出：offer在一定时间到时退出不添加，poll在一定时间到时退出不再获取。<br>如果是无界阻塞队列，队列不可能会出现满的情况，所以使用put或offer方法永远不会被阻塞，而且使用offer方法时，该方法永远返回true。</strong></p>
<h2 id="ArrayBlockingQueue"><a href="#ArrayBlockingQueue" class="headerlink" title="ArrayBlockingQueue"></a>ArrayBlockingQueue</h2><p><strong>由数组结构构成的有界阻塞队列，按照FIFO先进先出原则对元素进行排序，默认情况下不保证获取元素的线程顺序，可以在初始化的时候设置，<code>ArrayBlockingQueue queue = new ArrayBlockingQueue(5,true);</code></strong> 代码上由于我们在以前章节学过lock因此代码也比较简单，这里简单说下，首先的put（e）方法。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line">// 初始化</span><br><span class="line">    public ArrayBlockingQueue(int capacity, boolean fair) &#123;</span><br><span class="line">      // 容量不能小于等于0</span><br><span class="line">        if (capacity &lt;= 0)</span><br><span class="line">            throw new IllegalArgumentException();</span><br><span class="line">           // 创建数组</span><br><span class="line">        this.items = new Object[capacity];</span><br><span class="line">        // 生成公平还是非公平锁 如果不知道区别 可以看并发编程第四章</span><br><span class="line">        lock = new ReentrantLock(fair);</span><br><span class="line">        // 消费者 如果理解 可以看并发编程第四章</span><br><span class="line">        notEmpty = lock.newCondition();</span><br><span class="line">        // 生产者</span><br><span class="line">        notFull =  lock.newCondition();</span><br><span class="line">    &#125;</span><br><span class="line">public void put(E e) throws InterruptedException &#123;</span><br><span class="line">     // 插入数据不能为空</span><br><span class="line">        checkNotNull(e);</span><br><span class="line">        final ReentrantLock lock = this.lock;</span><br><span class="line">        // 加锁 可以被中断 </span><br><span class="line">        lock.lockInterruptibly();</span><br><span class="line">        try &#123;</span><br><span class="line">           // 判断是否满了 </span><br><span class="line">            while (count == items.length)</span><br><span class="line">              // 阻塞生产者</span><br><span class="line">                notFull.await();</span><br><span class="line">                //  不满则插入</span><br><span class="line">            enqueue(e);</span><br><span class="line">        &#125; finally &#123;</span><br><span class="line">            lock.unlock();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">      private void enqueue(E x) &#123;</span><br><span class="line">          // item 存放就是元素 </span><br><span class="line">        final Object[] items = this.items;</span><br><span class="line">        // 插入元素</span><br><span class="line">        items[putIndex] = x;</span><br><span class="line">        // 如果容量满了，被消费后，从数组的头部位置开始插入 </span><br><span class="line">        if (++putIndex == items.length)</span><br><span class="line">            putIndex = 0;</span><br><span class="line">        count++;</span><br><span class="line">        // 唤醒消费者</span><br><span class="line">        notEmpty.signal();</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>接下来是take（）<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line">public E take() throws InterruptedException &#123;</span><br><span class="line">// 获得当前锁对象</span><br><span class="line">       final ReentrantLock lock = this.lock;</span><br><span class="line">       // 加锁 可中断 </span><br><span class="line">       lock.lockInterruptibly();</span><br><span class="line">       try &#123;</span><br><span class="line">       // 判断是否为空</span><br><span class="line">           while (count == 0)</span><br><span class="line">            // 阻塞消费者</span><br><span class="line">               notEmpty.await();</span><br><span class="line">               // 获取元素</span><br><span class="line">           return dequeue();</span><br><span class="line">       &#125; finally &#123;</span><br><span class="line">       // 解锁</span><br><span class="line">           lock.unlock();</span><br><span class="line">       &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   private E dequeue() &#123;</span><br><span class="line">        // 获取当前元素</span><br><span class="line">       final Object[] items = this.items;</span><br><span class="line">      // 取出来</span><br><span class="line">       E x = (E) items[takeIndex];</span><br><span class="line">        // 赋为null</span><br><span class="line">       items[takeIndex] = null;</span><br><span class="line">       // 当下标为最后一个元素的时候，下标从头部重新开始获取</span><br><span class="line">       if (++takeIndex == items.length)</span><br><span class="line">           takeIndex = 0;</span><br><span class="line">           // 容量减一</span><br><span class="line">       count--;</span><br><span class="line">       if (itrs != null)</span><br><span class="line">           itrs.elementDequeued();</span><br><span class="line">           // 唤醒生产者生产</span><br><span class="line">       notFull.signal();</span><br><span class="line">       return x;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure></p>
<p>源码注释基本都写了，也很明确，下面阻塞队列原理基本差不多，有兴趣的可以看一下源码，如果不明白锁的可以看我以前写的文章。</p>
<h2 id="LinkedBlockingQueue"><a href="#LinkedBlockingQueue" class="headerlink" title="LinkedBlockingQueue"></a>LinkedBlockingQueue</h2><p><strong>由一个链表实现的有界阻塞队列，如果不设置队列大小默认为Integer.MAX_VALUE，也是按照FIFO原则。</strong></p>
<h2 id="PriorityBlockingQueue"><a href="#PriorityBlockingQueue" class="headerlink" title="PriorityBlockingQueue"></a>PriorityBlockingQueue</h2><p><strong>由一个支持优先级的无界阻塞队列，默认情况下是升序，也可以自定义compareTo（）方法来指定元素如何排序，需要注意的是不能保证同优先级元素的顺序。</strong></p>
<h2 id="DelayQueue"><a href="#DelayQueue" class="headerlink" title="DelayQueue"></a>DelayQueue</h2><p><strong>一个支持延时获取元素的无界队列，队列使用PriorityQueue来实现，插入的元素必须实现Delayedjiekou接口，在创建元素的时候指定多久后可以获取。</strong></p>
<h2 id="SynchronousQueue"><a href="#SynchronousQueue" class="headerlink" title="SynchronousQueue"></a>SynchronousQueue</h2><p><strong>一个不存储元素的阻塞队列，每一个put必须对应一个take，否则再次put，它支持线程公平访问，在初始化设置为true就可以，因此不存储元素，适合传递性场景，吞吐量高于ArrayBlockingQueue和LinkedBlockingQueue。</strong></p>
<h2 id="LinkedTransferQueue"><a href="#LinkedTransferQueue" class="headerlink" title="LinkedTransferQueue"></a>LinkedTransferQueue</h2><p><strong>由一个链表构成的无界阻塞队列，相比较其他阻塞队列多了transfer和tryTransfer方法。</strong><br>transfer方法表示如果当前有消费者正在等待接受元素（消费者使用take方法或者poll方法延时方法），transfer可以把生产的元素立即给消费者，如果没有消费则放入队列里。<br>tryTransfer方法表示生产者元素能否被消费者拿到，如果能则返回true，不能返回false。<br>相比较SynchronousQueue内部无法存储元素，当要添加元素的时候，需要阻塞；LinkedBolckingQueue 又使用了大量的锁，性能不高，LinkedTransferQueue类似与他们的结合品。一段代码说明transfer和tryTransfer。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">LinkedTransferQueue queue = new LinkedTransferQueue();</span><br><span class="line">       new Thread(()-&gt;&#123;</span><br><span class="line">           try &#123;</span><br><span class="line">               // 消费先取</span><br><span class="line">               System.out.println(queue.take());</span><br><span class="line">           &#125; catch (InterruptedException e) &#123;</span><br><span class="line">               e.printStackTrace();</span><br><span class="line">           &#125;</span><br><span class="line">       &#125;).start();</span><br><span class="line">       Thread.sleep(100);</span><br><span class="line">       // 生产者 生产元素</span><br><span class="line">       queue.tryTransfer(&quot;aa&quot;);</span><br><span class="line">       // 没有消费者消费 返回false</span><br><span class="line">       System.out.println(queue.tryTransfer(&quot;bb&quot;));</span><br></pre></td></tr></table></figure>
<h2 id="LinkedBlockingDeque"><a href="#LinkedBlockingDeque" class="headerlink" title="LinkedBlockingDeque"></a>LinkedBlockingDeque</h2><p><strong>是由一个链表组成的双向阻塞队列，它可以从队列的两端进行插入和删除，因为是双端，在多线程同时进队减少了一半的竞争。</strong>相比较于其他阻塞队列，LinkedBlockingDeque多了addFirst、addLast、offerFirst、offerLast、peekFirst和peekLast等方法。不用过多解释了，大概都能明白，由于操作大同小异，重点的方法都一样，只是底层实现不同，后续文章会单独说明。</p>
<h2 id="终极版——生产者消费者"><a href="#终极版——生产者消费者" class="headerlink" title="终极版——生产者消费者"></a>终极版——生产者消费者</h2><p>前面写过了两次生产者消费者，发现无论那种写起来都要考虑锁的使用，既然Jdk为我们提供了这种并发队列，那我们现在就来尝试一下。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">// 定义一个并发队列初始化为10</span><br><span class="line">       LinkedBlockingQueue&lt;Integer&gt; queue = new LinkedBlockingQueue(10);</span><br><span class="line">       // 开五个生产者</span><br><span class="line">       for (int i = 0; i &lt;5 ; i++) &#123;</span><br><span class="line">           new Thread(()-&gt;&#123;</span><br><span class="line">               while (true)&#123;</span><br><span class="line">                   try &#123;</span><br><span class="line">                       // 生产数据</span><br><span class="line">                       queue.put(new Random().nextInt(100));</span><br><span class="line">                   &#125; catch (InterruptedException e) &#123;</span><br><span class="line">                       e.printStackTrace();</span><br><span class="line">                   &#125;</span><br><span class="line">               &#125;</span><br><span class="line">           &#125;).start();</span><br><span class="line">       &#125;</span><br><span class="line">       // 开10个消费者</span><br><span class="line">       for (int i = 0; i &lt;10 ; i++) &#123;</span><br><span class="line">           new Thread(()-&gt;&#123;</span><br><span class="line">               while (true)&#123;</span><br><span class="line">                   try &#123;</span><br><span class="line">                       // 消费数据</span><br><span class="line">                       System.out.println(queue.take());</span><br><span class="line">                   &#125; catch (InterruptedException e) &#123;</span><br><span class="line">                       e.printStackTrace();</span><br><span class="line">                   &#125;</span><br><span class="line">               &#125;</span><br><span class="line">           &#125;).start();</span><br><span class="line">       &#125;</span><br></pre></td></tr></table></figure>
<p>代码量少多了，并且不用自己来控制锁了，手写生产者消费者如此简单。如有不对，还能指出。</p>

      
    </div>
    
    
    
	<div>
      
        
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>
  
  <!-- JS库 sweetalert 可修改路径 -->
  <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  <p><span>本文标题:</span><a href="/blog/2019/05/28/Java并发编程六并发队列/">Java并发编程六并发队列</a></p>
  <p><span>文章作者:</span><a href="/" title="访问 zhaoSir 的个人博客">zhaoSir</a></p>
  <p><span>发布时间:</span>2019年05月28日 - 19:07</p>
  <p><span>最后更新:</span>2019年05月28日 - 19:13</p>
  <p><span>原始链接:</span><a href="/blog/2019/05/28/Java并发编程六并发队列/" title="Java并发编程六并发队列">https://zgsir.gitee.io/blog/2019/05/28/Java并发编程六并发队列/</a>
    <span class="copy-path" title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="https://zgsir.gitee.io/blog/2019/05/28/Java并发编程六并发队列/" aria-label="复制成功！"></i></span>
  </p>
  <p><span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
      $(".fa-clipboard").click(function(){
      clipboard.on('success', function(){
        swal({   
          title: "",   
          text: '复制成功',
          icon: "success", 
          showConfirmButton: true
          });
        });
    });  
</script>

      
</div>
   <div>
    
    <div>
    
        <div style="text-align:center;color: #111;font-size:16px;">-------------------------------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------------------------------</div>
    
</div>
    
    </div>
   

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/并发队列/" rel="tag"><i class="fa fa-tag"> </i> 并发队列</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2019/05/27/Java并发编程五Atomic原子类/" rel="next" title="Java并发编程五Atomic原子类">
                <i class="fa fa-chevron-left"></i> Java并发编程五Atomic原子类
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2019/05/30/Java并发编程七ReentrantReadWriteLock和StampedLock/" rel="prev" title="Java并发编程七ReentrantReadWriteLock和StampedLock">
                Java并发编程七ReentrantReadWriteLock和StampedLock <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80NDMyMC8yMDg1Mw=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/blog/images/head.jpeg" alt="zhaoSir">
            
              <p class="site-author-name" itemprop="name">zhaoSir</p>
              <p class="site-description motion-element" itemprop="description">让人迷茫的原因的只有一个，那就是本该拼搏的年纪，想得太多，做得太少。</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">10</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">2</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#并发队列的类型"><span class="nav-number">1.</span> <span class="nav-text">并发队列的类型</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#ConcurrentLinkedQueue"><span class="nav-number">2.</span> <span class="nav-text">ConcurrentLinkedQueue</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#阻塞队列"><span class="nav-number">3.</span> <span class="nav-text">阻塞队列</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#方法说明"><span class="nav-number">3.1.</span> <span class="nav-text">方法说明</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#ArrayBlockingQueue"><span class="nav-number">3.2.</span> <span class="nav-text">ArrayBlockingQueue</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#LinkedBlockingQueue"><span class="nav-number">3.3.</span> <span class="nav-text">LinkedBlockingQueue</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#PriorityBlockingQueue"><span class="nav-number">3.4.</span> <span class="nav-text">PriorityBlockingQueue</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#DelayQueue"><span class="nav-number">3.5.</span> <span class="nav-text">DelayQueue</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#SynchronousQueue"><span class="nav-number">3.6.</span> <span class="nav-text">SynchronousQueue</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#LinkedTransferQueue"><span class="nav-number">3.7.</span> <span class="nav-text">LinkedTransferQueue</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#LinkedBlockingDeque"><span class="nav-number">3.8.</span> <span class="nav-text">LinkedBlockingDeque</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#终极版——生产者消费者"><span class="nav-number">3.9.</span> <span class="nav-text">终极版——生产者消费者</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<script type="text/javascript" src="/blog/js/src/love.js"></script>
<div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zhaoSir</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">博客字总数&#58;</span>
    
    <span title="博客字总数">20.8k</span>
  
  
</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  

  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

<script src="/blog/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","model":{"jsonPath":"/blog/live2dw/assets/koharu.model.json"},"display":{"position":"right","width":150,"height":320},"mobile":{"show":true},"log":false,"tagMode":false});</script></body>
</html>
